package edu.lingnan.rili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.lingnan.rili.mapper.MatchMapper;
import edu.lingnan.rili.pojo.Match;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.lingnan.rili.mapper.AwardedMapper;
import edu.lingnan.rili.pojo.Awarded;
import edu.lingnan.rili.pojo.Match;
import edu.lingnan.rili.pojo.Uploading;
import edu.lingnan.rili.mapper.UploadingMapper;
import edu.lingnan.rili.service.UploadingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.lingnan.rili.vo.UploadingVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import edu.lingnan.rili.utils.Result;
import edu.lingnan.rili.utils.ScheduledData;
import edu.lingnan.rili.utils.UploadUtils;
import edu.lingnan.rili.vo.OtherBonusPointsViewPages;
import edu.lingnan.rili.vo.PersonalInformation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈世杰
 * @since 2022-01-23
 */
@Service
public class UploadingServiceImpl extends ServiceImpl<UploadingMapper, Uploading> implements UploadingService {

    @Autowired
    private UploadingMapper uploadingMapper;

    @Autowired
    private MatchMapper matchMapper;

    @Autowired
    private ScheduledData scheduledData;

    @Resource
    private AwardedMapper awardedMapper;

    @Override
    public UploadingVo selectById(Serializable id, String stateId) {
        // 新建一个QueryWrapper对象
        QueryWrapper<Uploading> wrapper = new QueryWrapper<>();
        // 查询match之外的字段
        wrapper.select(Uploading.class, item-> !"match".equals(item.getColumn()));

        // 定义条件Map
        Map<String, Object> map = new HashMap<>();
        map.put("state_id", stateId);
        map.put("uploading_id", id);
        // 添加查询条件
        wrapper.allEq(map);
        Uploading uploading = uploadingMapper.selectOne(wrapper);
        UploadingVo uploadingVo = new UploadingVo();

        // 对查询结果进行判空
        if (!ObjectUtils.isEmpty(uploading)) {
            BeanUtils.copyProperties(uploading, uploadingVo);
            // 查询获奖人
            Match match = matchMapper.selectById(uploading.getUsersId());
            BeanUtils.copyProperties(match, uploadingVo);
            return uploadingVo;
        }
        return null;
    }

    @Override
    public List<Object> getUploadingIdNotReviewed() {
        QueryWrapper<Uploading> wrapper = new QueryWrapper<>();
        wrapper.select("uploading_id");
        // 查询待审核的数据
        wrapper.eq("state_id", Uploading.PENDING_REVIEW);
        List<Object> uploadingIdList = uploadingMapper.selectObjs(wrapper);
        System.out.println(uploadingIdList);
        if (!ObjectUtils.isEmpty(uploadingIdList)) {
            return uploadingIdList;
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param file 图片
     * @return 返回一个json，其中包括图片在服务器的访问地址
     */
    @Override
    public Result uploadingPhoto(MultipartFile file, HttpSession session) {

        Result result = new Result();
        if (ObjectUtils.isNotEmpty(file) && file.getSize() > 0) {//判断文件不为空和大小

            /*
             *以该学生的学号+时间戳作为命名
             */
            //调用工具类完成文件上传,将这个imagePath存进数据库里面，这个就是查看图片的地址

            //在session中获取match信息
            Match match = (Match) session.getAttribute("match");

            //判断session是否已过期
            if (match == null) {
                result.setResultCode(203);
                result.setMessage("会话已过期，请重新登录");
                return result;
            }

            //获取学号信息
            String usersId = match.getUsersId();

            String imagePath = UploadUtils.upload(file, usersId);
            System.out.println(imagePath);
            //判断如果不是图片格式则返回
            if (imagePath.equals("notPhoto")) {
                result.setResultCode(201);
                result.setMessage("上传失败，上传的文件类型不正确,请确保上传的文件格式为.jpg,.png,.jpeg！");
                return result;
            }
            if (imagePath != null) {
                //创建一个HashMap用来存放图片路径
                HashMap hashMap = new HashMap();
                hashMap.put("src", imagePath);
                result.setResultCode(200);
                result.setMessage("上传成功");
                result.setData(hashMap);
            } else {
                result.setResultCode(201);
                result.setMessage("上传失败");
            }
        } else {
            result.setResultCode(202);
            result.setMessage("没有上传图片");
        }
        return result;
    }

    /**
     * 其他加分项页面上传controller
     *
     * @param projectName 项目名称
     * @param projectType 类别
     * @return 返回一个json
     */
    @Override
    public Result otherBonusUpload(MultipartFile file, String projectName, String projectType, Double score, HttpSession session) {

        Match match = (Match) session.getAttribute("match");
        int row;
        if ("".equals(projectName) || "".equals(projectType) ||score==null
                || projectName == null || projectType == null) {

            return new Result(202, "申请失败，提交信息不完整");
        }
        if (match == null) {
            return new Result(203, "会话已过期，请重新登录");
        }

        if (ObjectUtils.isNotEmpty(file) && file.getSize() > 0) {//判断文件不为空和大小
            String imagePath = UploadUtils.upload(file, match.getUsersId());
            System.out.println(imagePath);
            //判断如果不是图片格式则返回
            if (imagePath.equals("notPhoto")) {
                Result result = new Result
                        (201, "上传失败，上传的文件类型不正确,请确保上传的文件格式为.jpg,.png,.jpeg！");
                return result;
            }

            //获取时间戳
            String timeStamp = getTimeStamp();

            //获取用户学号
            String usersId = match.getUsersId();

            //获取时间
            LocalDateTime l = LocalDateTime.now();
            System.out.println("otherBonusUpload测试时间格式" + l);

            //new一个uploading对象，并赋值
            Uploading uploading = new Uploading();
            uploading.setUploadingId(timeStamp).setGameName(projectName)
                    .setMaterials(imagePath).setProjectType(projectType)
                    .setUsersId(usersId).setUploadingType(scheduledData.getUploadingTypeOtherBonusPoints())
                    .setUploadingTime(l).setStateId(scheduledData.getStateIdNotApproved());

            System.out.println("测试预设数据是否可以获取；" + scheduledData.getStateIdAdopt());

            //将uploading对象数据插入到数据库中
            row = uploadingMapper.insert(uploading);

            //将基本信息插入到加分表
            Awarded awarded = new Awarded();
            awarded.setAddtype(projectType).setScore(score).setUploadingId(timeStamp);
            int insert = awardedMapper.insert(awarded);
        }else{
            Result result = new Result(204, "没有上传图片证明材料，请重新上传！");
            return result;
        }


        return judgmentResult(row);
    }

    /**
     * 其他比赛奖项页面上传controller
     *
     * @param matchName    比赛名称
     * @param prizeAwarded 比赛名次
     * @return 返回一个json
     */
    @Override
    public Result otherMatchUpload
    (MultipartFile file, String matchName, String projectType,
     Double score, String prizeAwarded, HttpSession session) {
        Match match = (Match) session.getAttribute("match");
        int row;
        if ("".equals(matchName) || "".equals(prizeAwarded) || score == null
                || matchName == null || prizeAwarded == null) {

            return new Result(202, "申请失败，提交信息不完整");
        }

        if (match == null) {
            return new Result(203, "会话已过期，请重新登录");
        }

        if (ObjectUtils.isNotEmpty(file) && file.getSize() > 0) {//判断文件不为空和大小
            String imagePath = UploadUtils.upload(file, match.getUsersId());
            System.out.println(imagePath);
            //判断如果不是图片格式则返回
            if (imagePath.equals("notPhoto")) {
                Result result = new Result
                        (201, "上传失败，上传的文件类型不正确,请确保上传的文件格式为.jpg,.png,.jpeg！");
                return result;
            }

            //获取时间戳
            String timeStamp = getTimeStamp();

            //获取用户学号
            String usersId = match.getUsersId();

            //获取时间
            LocalDateTime l = LocalDateTime.now();
            System.out.println("otherBonusUpload测试时间格式" + l);

            //new一个uploading对象，并赋值
            Uploading uploading = new Uploading();
            uploading.setUploadingId(timeStamp).setGameName(matchName)
                    .setMaterials(imagePath).setUsersId(usersId).setProjectType(projectType)
                    .setGameRanking(prizeAwarded).setUploadingType(scheduledData.getUploadingTypeOtherGames())
                    .setUploadingTime(l).setStateId(scheduledData.getStateIdNotApproved());

            //将uploading对象数据插入到数据库中
            row = uploadingMapper.insert(uploading);
            //将基本信息插入到加分表
            Awarded awarded = new Awarded();
            awarded.setAddtype(projectType).setScore(score).setUploadingId(timeStamp);
            int insert = awardedMapper.insert(awarded);
        }else {
            Result result = new Result(204, "没有上传图片证明材料，请重新上传！");
            return result;
        }

        return judgmentResult(row);
    }

    /**
     * 这是一个查询其他加分项申请记录的controller
     *
     * @return
     */
    @Override
    public Result<List<OtherBonusPointsViewPages>> queryOtherExtraPointsApplyRecord(HttpSession session) {
        return query(session, scheduledData.getUploadingTypeOtherBonusPoints());
    }

    /**
     * 这是一个查询其他比赛申请记录的controller
     *
     * @return
     */
    @Override
    public Result<List<OtherBonusPointsViewPages>> queryOtherGamesApplyRecord(HttpSession session) {

        return query(session, scheduledData.getUploadingTypeOtherGames());
    }

    /**
     * 这是一个查看个人上传记录的controller
     *
     * @param session
     * @return
     */
    @Override
    public Result<PersonalInformation> queryingPersonalUploadingRecords(HttpSession session, String uploadingId) {
        //获取个人信息
        Match match = (Match) session.getAttribute("match");
        if(match==null){
            Result result = new Result(203,"会话已过期，请重新登录");
            return result;
        }

        //通过uploadingId获取数据
        QueryWrapper<Uploading> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uploading_id", uploadingId);
        Uploading uploading = uploadingMapper.selectOne(queryWrapper);
        if (uploading == null) {
            Result result = new Result(204, "没有数据，请联系工作人员！");
            return result;
        }

        //处理数据（空）
        PersonalInformation personalInformation = new PersonalInformation();
        personalInformation.setGameName(uploading.getGameName()).setMaterials(uploading.getMaterials())
                .setName(match.getUsersName()).setUsersId(match.getUsersId())
                .setProjectType(uploading.getProjectType());
        //封装
        Result<PersonalInformation> result = new Result<>(200, "查询成功");
        result.setData(personalInformation);
        return result;
    }

    /**
     * 这是一个申请记录查询方法（通过type控制查询的是什么类型的申请记录 ）
     *
     * @param session
     * @param type    项目类型
     * @return
     */
    public Result<List<OtherBonusPointsViewPages>> query(HttpSession session, String type) {
        Result result = new Result();
        //通过session获取学生id
        Match match = (Match) session.getAttribute("match");
        //判断session是否已过期,若过期则返回会话过期result
        if (match == null) {
            return returnSessionIfNull(result);
        }
        //获取学生上传的数据信息
        QueryWrapper<Uploading> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users_id", match.getUsersId());
        List<Uploading> uploadings = uploadingMapper.selectList(queryWrapper);
        //判断是否查询结果为空，若为空直接返回，若不为空则继续
        if (uploadings == null || uploadings.size() == 0) {
            return returnListIfNull(result);
        }
        //通过循环获取需要的数据信息
        List<OtherBonusPointsViewPages> list = new ArrayList<>();
        processingData(type, uploadings, list, match);
        result.setResultCode(200);
        result.setMessage("查询成功");
        result.setData(list);
        return result;
    }

    /**
     * 这是一个返回会话过期result的方法
     */
    public Result returnSessionIfNull(Result result) {
        result.setResultCode(203);
        result.setMessage("会话已过期，请重新登录");
        return result;
    }

    /**
     * 这是一个返回查询结果为null的result方法
     */
    public Result returnListIfNull(Result result) {
        result.setResultCode(204);
        result.setMessage("没有查询到记录！");
        return result;
    }

    /**
     * 这是一个通过判断UploadingType属性处理数据的方法
     *
     * @param type       :加分类型
     * @param uploadings ：查询出来的结果集
     * @param list       ：处理后的数据存放的集合
     * @param match      ：从session中获取的
     */
    public void processingData
    (String type, List<Uploading> uploadings, List<OtherBonusPointsViewPages> list, Match match) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        for (Uploading uploading : uploadings) {
            //判断是否为其他加分的类型
            if (uploading.getUploadingType().equals(type)) {
                OtherBonusPointsViewPages otherBonusPointsViewPages = new OtherBonusPointsViewPages();
                otherBonusPointsViewPages.setName(match.getUsersName())
                        .setUploadingId(uploading.getUploadingId())
                        .setProjectName(uploading.getGameName())
                        .setProjectType(uploading.getProjectType())
                        .setUploadingTime(dtf.format(uploading.getUploadingTime()))
                        .setState(uploading.getStateId()).setStateCause(uploading.getStateCause())
                        .setMaterials(uploading.getMaterials());
                list.add(otherBonusPointsViewPages);
            }
            continue;
        }
    }

    /**
     * 获取当前时间并作为时间戳
     */
    public String getTimeStamp() {
        //时间格式化格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间并作为时间戳
        String timeStamp = simpleDateFormat.format(new Date());
        return timeStamp;
    }

    /**
     * 判断数据是否插入成功
     */
    public Result judgmentResult(int row) {
        Result result = new Result();
        if (row != 0) {
            result.setResultCode(200);
            result.setMessage("上传成功");
        } else {
            result.setResultCode(201);
            result.setMessage("上传失败");
        }
        return result;
    }


}
